package com.example.modifyphototime


import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loper7.date_time_picker.dialog.CardDatePickerDialog


/*remark：本想修改图库照片的时间字段，经测试：android10以下可以修改，android10以上很多字段只可读，不能修改
                                      android10系统的操作权限暂时不知道怎么申请
 */

class MainActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var photoAdapter: PhotoAdapter
    private val REQUEST_CODE_PERMISSION = 1001


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)

        checkPermissions()
    }

    private fun checkPermissions() {
        //Android11及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                val intent: Intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.setData(Uri.parse("package:" + this.packageName))
                startActivityForResult(intent, REQUEST_CODE_PERMISSION)
            }
        }
        val permissions = arrayOf(
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        )
        val permissionsNeeded = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        if (permissionsNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsNeeded.toTypedArray(), REQUEST_CODE_PERMISSION)
        }else{
            loadImages()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadImages()
            } else {
                Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show()
            }
        }
    }


    private fun loadImages() {
        val photos = mutableListOf<PhotoItem>()

        val projection = arrayOf(MediaStore.Images.Media._ID,
                                MediaStore.Images.Media.DATE_ADDED,
                                MediaStore.Images.Media.DATE_TAKEN,
                                MediaStore.Images.Media.DATA)
        val sortOrder = "${MediaStore.Images.Media.DATE_TAKEN} DESC"  // 按日期降序排列
        val cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, sortOrder)
        cursor?.use {
            while (it.moveToNext()) {
                val id = it.getLong(0)
                val timestamp = it.getLong(2)
                //val data = it.getString(3)

                val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
                photos.add(PhotoItem(uri, timestamp))
            }
        }

        photoAdapter = PhotoAdapter(photos)
        recyclerView.adapter = photoAdapter
        photoAdapter.setClickInterface(object : PhotoAdapter.ClickInterface{
            override fun onDateClick(uri: Uri, time: Long) {
                CardDatePickerDialog.builder(this@MainActivity)
                    .setTitle("modify time")
                    .setDefaultTime(time)
                    .showBackNow(false)
                    .showDateLabel(true)
                    .showFocusDateInfo(false)
                    .setOnChoose("选择",object :CardDatePickerDialog.OnChooseListener{
                        override fun onChoose(millisecond: Long) {
                            updatePhotoDate(uri, millisecond)
                        }
                    })
                    .setOnCancel("关闭",object :CardDatePickerDialog.OnCancelListener{
                        override fun onCancel() {
                        }
                    }).build().show()            }
        })
    }

    private fun updatePhotoDate(uri: Uri, newTimestamp: Long) {
        try {
            val values = ContentValues().apply {
                //put(MediaStore.Images.Media.DATE_ADDED, newTimestamp / 1000) // 转换为秒
                put(MediaStore.Images.Media.DATE_TAKEN, newTimestamp)
                //put(MediaStore.Images.Media.IS_FAVORITE, 1)
                //put(MediaStore.Images.Media.DISPLAY_NAME, "aa")
            }
            val rowsAffected = contentResolver.update(uri, values, null, null)
            //val rowsAffected = contentResolver.delete(uri,null,null)
            if (rowsAffected > 0) {
                Toast.makeText(this, "success", Toast.LENGTH_SHORT).show()
                loadImages()
            } else {   //当前字段在该版本不可修改
                Toast.makeText(this, "系统版本过高，请降至9", Toast.LENGTH_SHORT).show()
            }
        } catch (exception: SecurityException) {
            exception.printStackTrace()
            Toast.makeText(this, "请申请应用管理权限", Toast.LENGTH_LONG).show()
        }
    }
}
